import { createRouter, createWebHistory } from 'vue-router'
import UserList from '../pages/UserList.vue'
import RoleList from '../pages/RoleList.vue'
import Settings from '../pages/Settings.vue'
import Login from '../pages/Login.vue'
import MenuList from '../pages/MenuList.vue'
import HospitalList from '../pages/HospitalList.vue'
import ConfigList from '../pages/ConfigList.vue'
import DeviceList from '../pages/DeviceList.vue'
import LogList from '../pages/LogList.vue'
import DrugCatalog from '../pages/DrugCatalog.vue'
import CountyList from '../pages/CountyList.vue'
import DrugPermissions from '../pages/DrugPermissions.vue'
import UsageMonitor from '../pages/UsageMonitor.vue'
import SpeciaPrescription from '../pages/SpecialPrescription.vue'
import PrescriptionReview from '../pages/PrescriptionReview.vue'
import SpecialLibraryMonitor from '../pages/SpecialLibraryMonitor.vue'
import ReplenishmentRequest from '../pages/ReplenishmentRequest.vue'
import PatientMedicationRecords from '../pages/PatientMedicationRecords.vue'
import EmptyBottleReturn from '../pages/EmptyBottleReturn.vue'
import ConsumptionAnalysis from '../pages/ConsumptionAnalysis.vue'
import DoctorRanking from '../pages/DoctorRanking.vue'

// sleep module pages
import SleepEvaluation from '../pages/SleepEvaluation.vue'
import SleepDiagnosis from '../pages/SleepDiagnosis.vue'
import SleepTreatmentPlan from '../pages/SleepTreatmentPlan.vue'
import SleepNonDrug from '../pages/SleepNonDrug.vue'
import SleepMedication from '../pages/SleepMedication.vue'
import SleepFollowup from '../pages/SleepFollowup.vue'

// youth module pages
import YouthScreening from '../pages/YouthScreening.vue'
import YouthAssessment from '../pages/YouthAssessment.vue'
import IndividualTreatmentPlan from '../pages/IndividualTreatmentPlan.vue'
import PsychotherapyIntervention from '../pages/PsychotherapyIntervention.vue'
import FamilySystemIntervention from '../pages/FamilySystemIntervention.vue'
import CrisisIntervention from '../pages/CrisisIntervention.vue'

// firefighter module pages
import FirefighterProfiles from '../pages/FirefighterProfiles.vue'
import FirefighterAssessment from '../pages/FirefighterAssessment.vue'
import FirefighterCrisis from '../pages/FirefighterCrisis.vue'
import FirefighterIntervention from '../pages/FirefighterIntervention.vue'
import FirefighterTraining from '../pages/FirefighterTraining.vue'
import FirefighterStats from '../pages/FirefighterStats.vue'

// special-population module pages
import Vulnerable from '../pages/Vulnerable.vue'
import Developmental from '../pages/Developmental.vue'
import Addiction from '../pages/Addiction.vue'
import Perinatal from '../pages/Perinatal.vue'
import Elderly from '../pages/Elderly.vue'
import ChildrenYouth from '../pages/ChildrenYouth.vue'

// neuro-modulation module pages
import NeuroModulationAssessment from '../pages/NeuroModulationAssessment.vue'
import NeuroModulationProtocols from '../pages/NeuroModulationProtocols.vue'
import NeuroModulationDevices from '../pages/NeuroModulationDevices.vue'

import TotalOverview from '../pages/TotalOverview.vue'

// CountyList will be lazy-loaded in the route definition to avoid static import issues

// paths that should always be public (no auth required)
const publicRoutes = new Set<string>([
  '/login'
])

const routes = [
  { path: '/login', name: 'Login', component: Login, meta: { requiresAuth: false } },
  { path: '/', redirect: '/dashboard' },
  { path: '/dashboard', name: 'Dashboard', component: TotalOverview },
  { path: '/hospitals', name: 'HospitalList', component: HospitalList },
  { path: '/devices', name: 'DeviceList', component: DeviceList },
  { path: '/logs', name: 'LogList', component: LogList },
  { path: '/hospitals', name: 'HospitalList', component: HospitalList },
  { path: '/counties', name: 'CountyList', component: CountyList },
  { path: '/users', name: 'UserList', component: UserList },
  { path: '/roles', name: 'RoleList', component: RoleList },
  { path: '/configs', name: 'ConfigList', component: ConfigList },
  { path: '/menus', name: 'MenuList', component: MenuList },
  { path: '/drugCatalog', name: 'DrugCatalog', component: DrugCatalog},
  {path: '/drugPermissions', name: 'DrugPermissions', component: DrugPermissions},
  {path: '/usageMonitor', name: 'UsageMonitor', component: UsageMonitor},
  {path: '/specialPrescription', name: 'SpeciaPrescription', component: SpeciaPrescription},
  {path : '/prescriptionReview', name: 'PrescriptionReview', component: PrescriptionReview},
  { path: '/specialLibrary', name: 'SpecialLibraryMonitor', component: SpecialLibraryMonitor },
  { path: '/replenishmentRequests', name: 'ReplenishmentRequest', component: ReplenishmentRequest },
  { path: '/patientMedRecords', name: 'PatientMedicationRecords', component: PatientMedicationRecords },
  { path: '/emptyBottleReturns', name: 'EmptyBottleReturn', component: EmptyBottleReturn },
  { path: '/consumptionAnalysis', name: 'ConsumptionAnalysis', component: ConsumptionAnalysis },
  { path: '/doctorRanking', name: 'DoctorRanking', component: DoctorRanking },

  // youth management routes
  { path: '/screening', name: 'YouthScreening', component: YouthScreening },
  { path: '/assessment', name: 'YouthAssessment', component: YouthAssessment },
  { path: '/treatmentPlan', name: 'IndividualTreatmentPlan', component: IndividualTreatmentPlan },
  { path: '/psychotherapy', name: 'PsychotherapyIntervention', component: PsychotherapyIntervention },
  { path: '/familySystem', name: 'FamilySystemIntervention', component: FamilySystemIntervention },
  { path: '/crisis', name: 'CrisisIntervention', component: CrisisIntervention },

  // sleep management routes
  { path: '/evaluation', name: 'SleepEvaluation', component: SleepEvaluation },
  { path: '/diagnosis', name: 'SleepDiagnosis', component: SleepDiagnosis },
  { path: '/treatmentPlan', name: 'SleepTreatmentPlan', component: SleepTreatmentPlan },
  { path: '/nonDrug', name: 'SleepNonDrug', component: SleepNonDrug },
  { path: '/medication', name: 'SleepMedication', component: SleepMedication },
  { path: '/followup', name: 'SleepFollowup', component: SleepFollowup },

  // firefighter module routes
  { path: '/profiles', name: 'FirefighterProfiles', component: FirefighterProfiles },
  { path: '/assessment', name: 'FirefighterAssessment', component: FirefighterAssessment },
  { path: '/crisis', name: 'FirefighterCrisis', component: FirefighterCrisis },
  { path: '/intervention', name: 'FirefighterIntervention', component: FirefighterIntervention },
  { path: '/training', name: 'FirefighterTraining', component: FirefighterTraining },
  { path: '/stats', name: 'FirefighterStats', component: FirefighterStats },

  // special-population modules
  { path: '/childrenYouth', name: 'ChildrenYouth', component: ChildrenYouth },
  { path: '/elderly', name: 'Elderly', component: Elderly },
  { path: '/perinatal', name: 'Perinatal', component: Perinatal },
  { path: '/addiction', name: 'Addiction', component: Addiction },
  { path: '/developmental', name: 'Developmental', component: Developmental },
  { path: '/vulnerable', name: 'Vulnerable', component: Vulnerable },

  // neuro-modulation module routes
  { path: '/assessment', name: 'NeuroModulationAssessment', component: NeuroModulationAssessment },
  { path: '/protocols', name: 'NeuroModulationProtocols', component: NeuroModulationProtocols },
  { path: '/neuroModulationDevices', name: 'NeuroModulationDevices', component: NeuroModulationDevices },

  {path: '/totalOverview', name: 'TotalOverview', component: TotalOverview }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// lazy import of auth store inside guard to avoid circular import at module init
router.beforeEach(async (to, from, next) => {
  // allow routes that are in the explicit public list
  if (publicRoutes.has(to.path)) return next()
  // allow routes that explicitly opt out of auth check via meta
  if (to.meta && (to.meta as any).requiresAuth === false) return next()

  const { useAuthStore } = await import('../stores/auth')
  const auth = useAuthStore()
  if (!auth.isAuthenticated) {
    return next({ path: '/login', query: { redirect: to.fullPath } })
  }
  // if authenticated but menus not loaded, fetch them once
  if (!auth.menus || auth.menus.length === 0) {
    try {
      await auth.fetchMenus()
    } catch (e) {
      // failed to fetch menus (token maybe invalid) — force logout and redirect to login
      auth.logout()
      return next({ path: '/login' })
    }
  }
  next()
})

export default router
